<template>
  <div class="w-full">
    <div class="box p-1 mt-3 block sm:hidden">
      <van-cell is-link :title="selText" @click="showActionSheet = true"/>
      <van-action-sheet v-model:show="showActionSheet" :actions="actions" @select="onSelect"/>
    </div>
    <div
        class="hidden sm:grid grid-cols-1 2xl:grid-cols-5 xl:grid-cols-5 lg:grid-cols-5 gap-3 mt-3 ">
      <div class="col-span-1 sm:col-span-1 2xl:col-span-2 xl:col-span-2 lg:col-span-2 p-3 box intro-y">
        <!--        <chinaMap @selProvince="changeProvince" @getMapData="getMapData" :provinceAdcode="provinceAdcode"/>-->
        <chartMap :provinceAdcode="provinceAdcode" @selProvince="changeProvince" @selProvinceName="selProvinceName"/>
      </div>
      <div class="col-span-1 sm:col-span-1 2xl:col-span-3 xl:col-span-3 lg:col-span-3 p-3 box intro-y">
        <div
            class="flex justify-between items-center border-b border-slate-200/60 dark:border-darkmode-400 pb-5 mb-5"
        >
          <div class="font-medium text-lg truncate">选择省份</div>
          <div class="relative">
            <el-input
                v-model="searchQuery"
                style="width: 240px"
                @input="handleInput"
                placeholder="搜索"
                :prefix-icon="Search"
            />
            <div class="absolute bg-white border w-full z-50" v-if="searchResult.length>0">
              <div class="s-result p-2 cursor-pointer" v-for="(item,index) in searchResult"
                   @click="searchProvince(item)">
                {{ item.regionName }}
              </div>
            </div>
          </div>
        </div>
        <province @changeProvince="changeProvince" :selectArea="selectArea" :dataSource="dataSource"
                  :adcode="cityCode"/>
      </div>
    </div>
    <div class="grid grid-cols-1 2xl:grid-cols-5 gap-3 mt-3">
      <div class="col-span-1 sm:col-span-1 2xl:col-span-2 p-3 box intro-y">
        <!--        <threeDMap :adcode="adcode" :mapData="mapData" @changeCity="changeCity" :cityCode="cityCode"/>-->
        <chartAreaMap :provinceAdcode="provinceAdcode" @changeCity="changeCity"/>
      </div>
      <div class="col-span-1 sm:col-span-1 2xl:col-span-3 p-3 box intro-y">
        <wTable :tableData="tableData"/>
      </div>
    </div>
    <div class="grid grid-cols-12 gap-5 mt-5 pt-5 border-t intro-y">
      <div
          class="zoom-in col-span-12 sm:col-span-4 2xl:col-span-3 bg-gradient-to-br from-indigo-600 to-blue-300 rounded-xl p-4 shadow"
          v-if="todayWeather"
      >
        <div class="p-2 mb-2">
          <div class="text-center">
            <div class="leading-tight text-white">
              <font-awesome-icon :icon="['fas', 'location-dot']"/>
              {{ todayWeather?.cityName || "-" }}
            </div>
          </div>
          <div class="text-center">
            <div class="leading-tight text-gray-300">{{ todayWeather?.pickDate }}</div>
          </div>
        </div>
        <div class="p-1 mb-1">
          <div class="flex">
            <div class="flex-1 text-white text-7xl text-center">
              <font-awesome-icon :icon="['fas', 'cloud']"/>
              <!--              {{ todayWeather?.tempDiff}}-->
            </div>
          </div>
        </div>
        <div class="p-2 mb-2">
          <div class="text-center">
            <div class="leading-tight text-white text-lg">{{ todayWeather?.tempMax }}°/{{ todayWeather?.tempMin }}°
            </div>
            <div class="leading-tight text-white text-lg font-bold">{{ todayWeather?.statusName || "-" }}</div>
          </div>
        </div>
        <div class="text-xs text-white mb-1">今天</div>
        <div class="p-2 mb-2 bg-indigo-200 rounded-xl flex bg-opacity-20">
          <div class="flex-1 text-white text-center">
            <div class="text-xs">气温</div>
            <div><i class="bi bi-cloud-fill"></i></div>
            <div class="text-xs">{{ todayWeather?.tempMax }}° - {{ todayWeather?.tempMin }}°</div>
          </div>
          <div class="flex-1 text-white text-center">
            <div class="text-xs">风力</div>
            <div><i class="bi bi-sun"></i></div>
            <div class="text-xs">{{ todayWeather?.windName }}</div>
          </div>
          <div class="flex-1 text-white text-center">
            <div class="text-xs">天气状态</div>
            <div><i class="bi bi-cloud-fill"></i></div>
            <div class="text-xs">{{ todayWeather?.statusName || "-" }}</div>
          </div>
        </div>
      </div>
      <div
          class="zoom-in col-span-12 sm:col-span-4 2xl:col-span-3 bg-gradient-to-br from-indigo-600 to-blue-300 rounded-xl p-4 shadow"
          v-for="(item) in forecastList" :key="item.cityCode"
      >
        <div class="p-2 mb-2">
          <div class="text-center">
            <div class="leading-tight text-white">
              <font-awesome-icon :icon="['fas', 'location-dot']"/>
              {{ item.cityName }}
            </div>
          </div>
          <div class="text-center">
            <div class="leading-tight text-gray-300">{{ item.pickDate }}</div>
          </div>
        </div>
        <div class="p-1 mb-1">
          <div class="flex">
            <div class="flex-1 text-white text-7xl text-center">
              <font-awesome-icon :icon="['fas', 'cloud']"/>
            </div>
          </div>
        </div>
        <div class="p-2 mb-2">
          <div class="text-center">
            <div class="leading-tight text-white text-lg">{{ item.tempMax }}°/{{ item.tempMin }}°</div>
            <div class="leading-tight text-white text-lg font-bold">{{ item.statusName || "-" }}</div>
          </div>
        </div>
        <div class="text-xs text-white mb-1">预测：{{ item.dayLabel }}</div>
        <div class="p-2 mb-2 bg-indigo-200 rounded-xl flex bg-opacity-20">
          <div class="flex-1 text-white text-center">
            <div class="text-xs">气温</div>
            <div><i class="bi bi-cloud-fill"></i></div>
            <div class="text-xs">{{ item.tempMax }}° - {{ item.tempMin }}°</div>
          </div>
          <div class="flex-1 text-white text-center">
            <div class="text-xs">风力</div>
            <div><i class="bi bi-sun"></i></div>
            <div class="text-xs">{{ item.windName }}</div>
          </div>
          <div class="flex-1 text-white text-center">
            <div class="text-xs">天气状态</div>
            <div><i class="bi bi-cloud-fill"></i></div>
            <div class="text-xs">{{ item.statusName || "-" }}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, computed, onMounted} from "vue";
import threeDMap from "./threeDMap.vue";
import wTable from "./wTable.vue";
import province from "./province.vue";
import chinaMap from "./chinaMap.vue";
import chartMap from "./chartMap.vue"
import chartAreaMap from "./chartAreaMap.vue"
import {Search} from '@element-plus/icons-vue'
import {debounce} from 'lodash'
import {ActionSheet} from 'vant';
import * as $api from "@/api/api.js";

const provinceAdcode = ref(Number(localStorage.getItem("regionCode")));
const cityCode = ref(Number(localStorage.getItem("cityCode")));
const selText = ref("选择省份")
const dataSource = ref(null);
const showActionSheet = ref(false);
const tableData = ref([]);
const todayWeather = ref(null);
const forecastList = ref([]);
const userKey = ref(localStorage.getItem("userKey"));
const actions = ref([]);
const onSelect = (item) => {
  mapData.value = convertDataAtoB(item);
  selText.value = item.name;
  // 默认情况下点击选项时不会自动收起
  // 可以通过 close-on-click-action 属性开启自动收起
  showActionSheet.value = false;
};

const params = ref({
  today: new Date(),
  tomorrow: new Date(),
  afterTomorrow: new Date(),
  dayAfterTomorrow: new Date(),
});
const searchQuery = ref("");
const searchResult = ref([]);
const selectArea = ref("");
const adcode = ref("");
const mapData = ref(null);
const formatDate = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0"); // 月份从0开始，所以需要+1，并且保证两位数
  const day = String(date.getDate()).padStart(2, "0"); // 保证日期是两位数
  return `${year}-${month}-${day}`;
};
const dates = computed(() => ({
  today: formatDate(params.value.today),
  tomorrow: formatDate(params.value.tomorrow),
  afterTomorrow: formatDate(params.value.afterTomorrow),
  dayAfterTomorrow: formatDate(params.value.dayAfterTomorrow),
}));
params.value.tomorrow.setDate(params.value.today.getDate() + 1);
params.value.afterTomorrow.setDate(params.value.tomorrow.getDate() + 1);
params.value.dayAfterTomorrow.setDate(params.value.afterTomorrow.getDate() + 1);

onMounted(() => {
  getRegionList();
  // selectArea.value = localStorage.getItem("regionName");
});

// 获取省列表
const getRegionList = () => {
  $api.GetRegionList().then(res => {
    dataSource.value = res;
    actions.value = res.map(item => ({
      lat: item.lat,
      lon: item.lon,
      name: item.regionName,
      regionCode: item.regionCode,
    }));
    // 筛选出与登录返回省份相同的省份信息
    const filterData = res.filter(item => Number(item.regionCode) === provinceAdcode.value);
    console.log(filterData);
    mapData.value = convertDataAtoB(filterData[0]);
    getWeatherData(cityCode.value);
    getTodayWeather(cityCode.value);
    getForecast(cityCode.value);
  })
}
// 根据省查询城市
const queryCityByRegion = (item) => {
  $api.QueryCityByRegion({
    unitKey: "",
    userKey: userKey.value,
    key: ""
  }).then(res => {
    console.log(res);
  })
}
// 切换城市
const changeCity = (item) => {
  getWeatherData(item);
  getTodayWeather(item);
  getForecast(item);
};
// 获取市一周数据
const getWeatherData = (code) => {
  $api.QueryByCity({
    unitKey: "",
    userKey: userKey.value,
    num: 7,
    code: code
  }).then(res => {
    console.log(res);
    res.forEach(item => {
      item.pickDate = item.pickDate.substring(0, 10); // 只取前10个字符，即 'yyyy-mm-dd'
    });
    tableData.value = res;
  })
}
// 查询本日天气
const getTodayWeather = (code) => {
  $api.QueryToday({
    unitKey: "",
    userKey: userKey.value,
    code: code
  }).then(res => {
    res.pickDate = res.pickDate.substring(0, 10); // 只取前10个字符，即 'yyyy-mm-dd'
    todayWeather.value = res;
  })
}
// 查询未来三天数据
const getForecast = (code) => {
  $api.QueryForecast({
    unitKey: "",
    userKey: userKey.value,
    code: code
  }).then(res => {
    console.log(res);
    forecastList.value = addDayLabelsToWeatherData(res);
  })
}
// 格式化预测天气数据
const addDayLabelsToWeatherData = (weatherData) => {
  // 检查输入的有效性
  if (!Array.isArray(weatherData)) {
    throw new Error('weatherData must be an array.');
  }
  // 定义标签数组
  const labels = ["明天", "后天", "大后天"];
  // 获取需要处理的数据长度（以weatherData和labels的最小长度为准）
  const length = Math.min(weatherData.length, labels.length);
  // 复制一份新的数据数组，避免修改原始数据
  const result = weatherData.slice(0, length).map((item, index) => {
    // 创建一个新的对象，复制原对象的所有属性并添加新的标签属性
    const newItem = {
      ...item,
      dayLabel: labels[index]
    };
    // 格式化 pickDate 字段
    const pickDate = new Date(item.pickDate);
    newItem.pickDate = `${pickDate.getFullYear()}-${String(pickDate.getMonth() + 1).padStart(2, '0')}-${String(pickDate.getDate()).padStart(2, '0')}`;
    return newItem;
  });
  return result;
}
// 监听输入事件
const handleInput = () => {
  searchDebounced(searchQuery.value)
}
// 防抖后的搜索函数
const searchDebounced = debounce((query) => {
  if (!query) {
    searchResult.value = []
  } else {
    // 从dataSource中搜索符合query的数据
    searchResult.value = dataSource.value.filter((item) => item.regionName.toLowerCase().includes(query.toLowerCase()));
    // searchResult.value = ["北京市", "上海市"]
  }
}, 500) // 防抖延迟500ms


const changeProvince = (item) => {
  tableData.value = [];
  provinceAdcode.value = item.regionCode ? item.regionCode : item;
  mapData.value = convertDataAtoB(item);
};
const convertDataAtoB = (data) => {
  return {
    acroutes: [parseInt(100000)], // 假设acroutes是一个数组，元素为regionCode的整数值
    adcode: parseInt(data.regionCode), // 直接使用regionCode作为adcode
    center: [data.lon, data.lat], // 经度在前，纬度在后
    centroid: [data.lon, data.lat], // 同center
    childrenNum: null, // 数据A中没有提供，这里设置为null
    level: "province", // 根据regionName推断
    name: data.regionName, // 使用regionName
    parent: {adcode: 100000}, // 假设这是国家代码
    subFeatureIndex: null // 数据A中没有提供，这里设置为null
  };
}
// 点击搜索结果
const searchProvince = (item) => {
  searchQuery.value = item.regionName;
  selectArea.value = item.regionName;
  searchResult.value = [];
  mapData.value = convertDataAtoB(item);
  provinceAdcode.value = item.regionCode;
}
const selProvinceName = (item) => {
  selectArea.value = item;
}
const getMapData = (e) => {
  mapData.value = e;
}
</script>

<style lang="scss" scoped>
.s-result {
  transition: all 0.2s ease;

  &:not(:last-child) {
    border-bottom-width: 1px;
  }

  &:hover {
    background: #444f55;
    color: #ffffff;
  }
}
</style>